// packageA/pages/editSku/index.js
const util = require("./../../../utils/util.js");
Page({

    /**
     * 页面的初始数据{ id: 1, name: '推荐' }, 
     */
    data: {
        goodsId: '',
        categoryList: [
            { id: 1, name: '奶皮子酸奶' },{ id: 2, name: '特色口味' }, { id: 3, name: '大杯系列' },
            { id: 4, name: '小杯系列' },{ id: 5, name: '优惠套餐' }, { id: 6, name: '酸奶饮品' },
            { id: 7, name: '小吃搭配' }
        ],
        categoryIndex: 0,
        currentCategory: {},
        brandList: [
            { id: 1, name: '草原牧场' }, { id: 2, name: '雪山牦牛' },
            { id: 3, name: '黄金奶源' }
        ],
        brandIndex: 0,
        currentBrand: {},
        unitList: [
            { id: 1, name: '杯' }, { id: 2, name: '瓶' },
            { id: 3, name: '盒' }, { id: 4, name: '套' }
        ],
        unitIndex: 0,
        currentUnit: {},
        mediaList: [],
        goods: {
            name: '', subtitle: '', description: '',
            price: '', memberPrice: '', stock: '', spec: '500g*2盒',
            isRecommend: false, isNew: false, status: true
        }
    },
    //商品分类
    GetAllCategoriesAsync() {
        return wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.GetAllCategoriesAsync", {})
    },
    GetSkuByIdAsync(param) {
        return wx.Http.get("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetSkuByIdAsync", {
            skuId: param
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.GetAllCategoriesAsync().then((res) => {
            if (res.data) {
                // const mergedArray = this.data.categoryList.concat(res.data);
                this.setData({
                    categoryList: res.data,
                    // categoryIndex: res.data[0].id
                })
            }
        })

        const { id } = options
        this.setData({ goodsId: id })
        this.loadGoodsData(id)
    },
    loadGoodsData(id) {
        wx.showLoading({ title: '加载中...' })
        let myid = Number(id);
        this.GetSkuByIdAsync(myid).then((res) => {
            if (res.data) {
                this.initFormData(res.data)
                wx.hideLoading()
            }

        })
        // 模拟API请求
        // setTimeout(() => {
        //     const mockData = {
        //         id: '1001',
        //         name: '奶皮子酸奶（椰子味）',
        //         subtitle: '椰香浓郁，口感丝滑',
        //         brand: '草原牧场',
        //         category: '特色口味',
        //         description: '采用新鲜椰浆发酵，富含益生菌',
        //         price: 28.8,
        //         memberPrice: 25.9,
        //         unit: '杯',
        //         stock: 156,
        //         isRecommend: true,
        //         spec: '500g*2盒',
        //         isNew: false,
        //         status: true,
        //         images: [
        //             'https://xxx.xjdio.com/static/img/1.jpg',
        //             'https://xxx.xjdio.com/static/img/4.jpg'
        //         ]
        //     }

        //     this.initFormData(mockData)
        //     wx.hideLoading()
        // }, 800)
    },

    initFormData(data) {
        const categoryIndex = this.data.categoryList.findIndex(item => item.name === data.category)
        const brandIndex = this.data.brandList.findIndex(item => item.name === data.brand)
        const unitIndex = this.data.unitList.findIndex(item => item.name === data.unit)
        this.setData({
            goods: data,
            //  {
            //     name: data.name,
            //     subtitle: data.subtitle,
            //     description: data.description,
            //     price: data.price,
            //     memberPrice: data.memberPrice,
            //     stock: data.stock,
            //     isRecommend: data.isRecommend,
            //     isNew: data.isNew,
            //     spec: data.spec,
            //     status: data.status
            // },
            mediaList: data.mediasUrl || [],
            categoryIndex,
            brandIndex,
            unitIndex,
            currentCategory: this.data.categoryList[categoryIndex] || {},
            currentBrand: this.data.brandList[brandIndex] || {},
            currentUnit: this.data.unitList[unitIndex] || {}
        })
    },

    categoryChange(e) {
        const index = e.detail.value
        this.setData({
            categoryIndex: index,
            currentCategory: this.data.categoryList[index]
        })
    },

    brandChange(e) {
        const index = e.detail.value
        this.setData({
            brandIndex: index,
            currentBrand: this.data.brandList[index]
        })
    },

    unitChange(e) {
        const index = e.detail.value
        this.setData({
            unitIndex: index,
            currentUnit: this.data.unitList[index]
        })
    },

    // chooseMedia() {
    //     wx.chooseMedia({
    //         count: 9 - this.data.mediaList.length,
    //         mediaType: ['image'],
    //         success: (res) => {
    //             this.setData({
    //                 mediaList: this.data.mediaList.concat(res.tempFiles.map(item => item.tempFilePath))
    //             })
    //         }
    //     })
    // },
    chooseMedia(e) {
        console.log(e.currentTarget.dataset.id);
        const _this = this;
        wx.chooseMedia({
            count: 1,
            mediaType: ['image', 'video'],
            sizeType: ["compressed"],//"original",
            sourceType: ["album", "camera"],
            maxDuration: 180,
            success(res) {
                let dt1 = new Date();
                let dt2 = util.formatTime6(dt1);
                let params = {
                    tablename: "Product",
                    tableid: dt2,
                };
                wx.uploadFile({
                    url: wx._baseUrl + "/ApiAppService/Xncf.Xxgmall_ApiAppService.UploadMedia",
                    filePath: res.tempFiles[0].tempFilePath,
                    header: {
                        "content-type": "multipart/form-data",
                        accept: "application/json",
                    },
                    method: "POST",
                    imgType: 1,
                    name: "Zxrh", //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
                    formData: params, //HTTP 请求中其他额外的 form data
                    success: function (res) {
                        if (res.statusCode == 200) {
                            let datatemp = JSON.parse(res.data);
                            let arr = datatemp.data;//.split(","); //分割数组
                            if (e.currentTarget.dataset.id == 2) {
                                if (e.currentTarget.dataset.index >= 0) {
                                    _this.data.mediaList[e.currentTarget.dataset.index] = arr;
                                } else {
                                    _this.data.mediaList.push(arr)
                                }
                                _this.setData({
                                    mediaList: _this.data.mediaList
                                })
                            } else if (e.currentTarget.dataset.id == 1) {
                                _this.setData({
                                    'goods.imageUrl': arr
                                })
                            }

                        } else {
                            console.log(res)
                            wx.showToast({
                                title: "上传有误",
                            });
                        }
                    },
                    fail: (err) => {
                        wx.showToast({
                            title: "上传失败!",
                        });
                    },
                });
            },
        });
    },
    removeImage(e) {
        const index = e.currentTarget.dataset.index
        const newList = [...this.data.mediaList]
        newList.splice(index, 1)
        this.setData({ mediaList: newList })
    },
    Deletefile(param1) {
        return wx.Http.post("/ApiAppService/Xncf.Xxgmall_ApiAppService.Deletefile", {
            DeletePic: param1,
        });
    },
    // 删除图片
    removePhoto(e) {
        const _this = this;
        // const index = e.currentTarget.dataset.index;
        var contactstemp = this.data.goods.imageUrl;
        // var item=contactstemp[index];
        wx.showModal({
            title: '提示',
            content: '是否确认删除',
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {

                    _this.Deletefile(contactstemp).then((res) => {
                        if (res.data) {
                            // contactstemp.splice(index, 1);
                            this.setData({ 'goods.imageUrl': '' });

                        }
                    })
                }
            }
        })

    },
    previewImage(e) {
        wx.previewImage({
            current: e.currentTarget.dataset.src,
            urls: this.data.mediaList
        })
    },

    toggleRecommend(e) {
        this.setData({ 'goods.isRecommend': e.detail.value })
    },

    toggleNew(e) {
        this.setData({ 'goods.isNew': e.detail.value })
    },

    toggleStatus(e) {
        this.setData({ 'goods.status': e.detail.value })
    },
    UpdateSkuAsync(param) {
        return wx.Http.post("/SkuAppService/Xncf.Xxgmall_SkuAppService.UpdateSkuAsync", param)
    },
    submitForm(e) {
        const formData = e.detail.value
        if (!formData.title) {
            wx.showToast({ title: '请填写商品标题', icon: 'none' })
            return
        }
        if (!formData.title) {
            wx.showToast({ title: '请填写商品标题', icon: 'none' })
            return
        }
        if (!this.data.goods.imageUrl) {
            wx.showToast({ title: '请上传主图', icon: 'none' })
            return
        }
        if (!formData.specifications) {
            wx.showToast({
                title: '请填写规格', icon: 'none'
            })
            return
        }
       let mycategoryid=Number(this.data.categoryIndex) ;
        const goodsData = {
            ...formData,
            id: Number(this.data.goodsId) ,
            category: this.data.currentCategory.name,
            brand: this.data.currentBrand.name,
            unit: this.data.currentUnit.name,
            category_Id:this.data.categoryList[mycategoryid].id,
            imageUrl:this.data.goods.imageUrl,
            mediasUrl: this.data.mediaList.toString(),
            isRecommend: this.data.goods.isRecommend,
            isNew: this.data.goods.isNew,
            status: this.data.goods.status,
            price:Number(formData.price),
            // stock:Number(formData.stock),
        }
        console.log(goodsData)
        wx.showLoading({ title: '保存中...' })
        this.UpdateSkuAsync(goodsData).then((res)=>{
            if(res.data){
                wx.hideLoading()
                let page = getCurrentPages();
                var prevPage = page[page.length - 2];  //上⼀个页⾯
                prevPage.onLoad();
                setTimeout(() => {
                    wx.navigateBack({
                        delta: 1,
                    });
                }, 500);
            }
        })
        // 模拟API请求
        // setTimeout(() => {
        //     wx.hideLoading()
        //     wx.showToast({ title: '保存成功', icon: 'success' })
        //     setTimeout(() => {
        //         wx.navigateBack()
        //     }, 1500)
        // }, 1000)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})